package com.yan.qing.bootoss.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.util.StringUtils;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.yan.qing.bootoss.pojo.AliOssProperties;
import com.yan.qing.bootoss.response.OssPolicyResultResponse;
import com.yan.qing.bootoss.service.AliOssService;
import com.yan.qing.bootoss.service.OssService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class AliOssServiceImpl implements OssService {
    private static Logger logger = LoggerFactory.getLogger(AliOssServiceImpl.class);



    @Override
    public OssPolicyResultResponse policy(String path, String bucketName) {
        AliOssProperties properties;
        OSSClient ossCli;
        //不传用默认bucket配置

        //从配置中心获取
        properties = new AliOssProperties();
        properties.setDomain("baidi");
        properties.setMaxSize(1000);
        properties.setExpire(1000000);
        ossCli = new OSSClient("", new DefaultCredentialProvider("", ""), null);


        OssPolicyResultResponse result = new OssPolicyResultResponse();
        // 存储目录
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //设置前端文件前缀路径
        String dir = path + "/" + sdf.format(new Date()) + "/";
        // 签名有效期
        long expireEndTime = System.currentTimeMillis() + properties.getExpire() * 1000;
        Date expiration = new Date(expireEndTime);
        // 文件大小
        long maxSize = properties.getMaxSize() * 1024 * 1024;
        try {
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, maxSize);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
            String postPolicy = ossCli.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String policy = BinaryUtil.toBase64String(binaryData);
            String signature = ossCli.calculatePostSignature(postPolicy);
            result.setAccessKeyId(ossCli.getCredentialsProvider().getCredentials().getAccessKeyId());
            result.setPolicy(policy);
            result.setSignature(signature);
            result.setDir(dir);
            result.setHost(properties.getDomain());
            result.setExpire(String.valueOf(expireEndTime / 1000));
        } catch (Exception e) {
            logger.error("签名生成失败", e);
        }
        return result;
    }
}
